package com.tjetc.service.impl;

import com.tjetc.domain.Close;
import com.tjetc.domain.CloseApply;
import com.tjetc.mapper.CloseApplyMapper;
import com.tjetc.mapper.CloseMapper;
import com.tjetc.mapper.SchedulingMapper;
import com.tjetc.service.CloseApplyService;
import com.tjetc.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CloseApplyServiceImpl implements CloseApplyService {
    @Resource
    private CloseApplyMapper closeApplyMapper;

    @Resource
    private CloseMapper closeMapper;

    @Resource
    private SchedulingMapper schedulingMapper;

    @Override
    public Result list() {
        // 只查询is_agree为null的申请
        List<CloseApply> list = closeApplyMapper.list();
        return Result.ok(list);
    }

    @Override
    public Result approve(Integer id, Integer adminId) {
        // 1. 获取申请详情
        CloseApply apply = closeApplyMapper.selectByPrimaryKey(id);
        if(apply == null) {
            return Result.fail("申请不存在");
        }

        // 2. 创建close记录
        Close close = new Close();
        close.setScheduleId(apply.getSchedulingId());
        close.setDesc(apply.getDesc());
        close.setTime(apply.getTime());
        close.setIsAgree(1); // 1表示同意
//        close.setHid(apply.getHospital().getId());
        close.setAdminId(adminId);

        // 3. 保存到close表
        closeMapper.insert(close);

        // 4. 更新scheduling状态为0(停诊)
        schedulingMapper.updateStateById(apply.getSchedulingId());

        // 5. 更新申请状态为已同意
        apply.setIsAgree(1);
        closeApplyMapper.updateByPrimaryKey(apply);

        return Result.ok("审批通过");
    }

    @Override
    public Result reject(Integer id, Integer adminId) {
        // 1. 获取申请详情
        CloseApply apply = closeApplyMapper.selectByPrimaryKey(id);
        if(apply == null) {
            return Result.fail("申请不存在");
        }

        // 2. 创建close记录
        Close close = new Close();
        close.setScheduleId(apply.getSchedulingId());
        close.setDesc(apply.getDesc());
        close.setTime(apply.getTime());
        close.setIsAgree(0); // 0表示拒绝
//        close.setHid(apply.getHospital().getId());
        close.setAdminId(adminId);

        // 3. 保存到close表
        closeMapper.insert(close);

        // 4. 更新申请状态为已拒绝
        apply.setIsAgree(0);
        closeApplyMapper.updateByPrimaryKey(apply);

        return Result.ok("审批拒绝");
    }

    @Override
    public Result add(CloseApply closeApply) {
        int rows=closeApplyMapper.add(closeApply);
        if (rows>0){
            return Result.ok(closeApply);
        }else {
            return Result.fail();
        }
    }
}